const fs     = require('fs');
const Koa    = require( 'koa');
const Router = require( 'koa-router');
const websocket     = require( 'koa-websocket');
const koa_static    = require( 'koa-static');
const sslify        = require( 'koa-sslify').default;
const bodyParser    = require( 'koa-bodyparser');

const ppy_cfg       = require('./ppy_xterm.json');
const {ppy_ws}      = require('./ppy_ws');
const {ppy_authapi} = require('./ppy_authapi');

const options = {
    key: fs.readFileSync(ppy_cfg.key_file),
    cert: fs.readFileSync(ppy_cfg.pem_file),
   }
const app_http   = new Koa()
//const app_ws     = websocket(app_http)
const app_ws     = websocket(app_http, {}, options)
app_http.use(sslify()) 
app_http.use(bodyParser());

const router     = new Router();
app_http.use(async (ctx, next) =>{
    await next();
    ctx.set("Access-Control-Allow-Origin", "*");
    ctx.set("Access-Control-Allow-Headers", "Content-Type");
    ctx.set("Access-Control-Allow-Methods", "*");
});

app_http.use(koa_static(__dirname + '/public', {
    index: false, 
    hidden: false,
    defer: true
}))

router.get('/term', ppy_ws);
router.get('/authapi', ppy_authapi);

app_ws.ws.use(router.routes());
app_http.use(router.routes());

app_http.listen(ppy_cfg.port, ppy_cfg.host, () => {
    console.log(`服务启动`);
    const ssh_asset_id = 'A33563FA7C7659D0';
    
    const docker_host  = 'localhost';
    const docker_container_id = 'c0ca3d72896b';

    console.log(`https://${ppy_cfg.host}:${ppy_cfg.port}/ppy_xterm.html?type=pty&asset_id=${ppy_cfg.pty_token}`);
    console.log(`https://${ppy_cfg.host}:${ppy_cfg.port}/ppy_xterm.html?type=ssh&asset_id=${ssh_asset_id}`);
    console.log(`https://${ppy_cfg.host}:${ppy_cfg.port}/ppy_xterm.html?type=docker&host=${docker_host}&container_id=${docker_container_id}`);
})
